package set

import (
	"abdis/datastruct/dict"
	"abdis/interface/datastruct"
	"abdis/lib/wildcard"
)

type Set struct {
	dict datastruct.Dict
}

func MakeSet() *Set {
	return &Set{
		dict: dict.MakeSimple(),
	}
}

func (s *Set) Add(val string) int {
	return s.dict.Put(val, nil)
}

func (s *Set) Remove(val string) int {
	_, ret := s.dict.Remove(val)
	return ret
}

func (s *Set) Has(val string) bool {
	_, exists := s.dict.Get(val)
	return exists
}

func (s *Set) Len() int {
	return s.dict.Len()
}

func (s *Set) ForEach(consumer datastruct.Consumer) {
	s.dict.ForEach(func(key string, val any) bool {
		return consumer(key, val)
	})
}

func (s *Set) Scan(cursor int, count int, pattern string) ([][]byte, int) {
	result := make([][]byte, 0)
	// TODO 实现不好
	match, err := wildcard.CompilePattern(pattern)
	if err != nil {
		return result, -1
	}

	s.ForEach(func(key string, val any) bool {
		if pattern == "*" || match.IsMatch(key) {
			result = append(result, []byte(key))
		}
		return true
	})
	return result, 0
}
